package com.openroom.ui;

import java.net.URL;

import org.apache.pivot.wtk.LinkButton;
import org.apache.pivot.wtk.content.ButtonData;

import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.model.ModelLocator;

public class RatingEventHandler implements EventHandler {
    LinkButton twoStarBtn;
    LinkButton oneStarBtn;
    LinkButton threeStarBtn;
    LinkButton fourStarBtn;
    LinkButton fiveStarBtn;

    public RatingEventHandler(LinkButton oneStarBtn, LinkButton twoStarBtn, LinkButton threeStarBtn,
            LinkButton fourStarBtn, LinkButton fiveStarBtn) {
        super();
        this.twoStarBtn = twoStarBtn;
        this.oneStarBtn = oneStarBtn;
        this.threeStarBtn = threeStarBtn;
        this.fourStarBtn = fourStarBtn;
        this.fiveStarBtn = fiveStarBtn;
    }

    @Override
    public void handle(ApplicationEvent event) {
        URL resource = MainWindow.class.getClassLoader().getResource(
                "com/openroom/ui/green_star.png");
        Integer data = ModelLocator.getInstance().getCurrentlySelectedImage().getRatingValue();
        resetAllStars();
        switch (data) {
        case 5:
            changeStarColor(resource, fiveStarBtn);
        case 4:
            changeStarColor(resource, fourStarBtn);
        case 3:
            changeStarColor(resource, threeStarBtn);
        case 2:
            changeStarColor(resource, twoStarBtn);
        case 1:
            changeStarColor(resource, oneStarBtn);
            break;
        default:
            break;
        }
    }

    private void resetAllStars() {
        URL unselected = MainWindow.class.getClassLoader().getResource(
                "com/openroom/ui/white_star.png");
        changeStarColor(unselected, fiveStarBtn);
        changeStarColor(unselected, fourStarBtn);
        changeStarColor(unselected, threeStarBtn);
        changeStarColor(unselected, twoStarBtn);
        changeStarColor(unselected, oneStarBtn);
    }

    public static void changeStarColor(URL resource, LinkButton button) {
        ButtonData buttonData = null;
        buttonData = (ButtonData) button.getButtonData();
        buttonData.setIcon(resource);
        button.repaint();
    }

    public static void setColor(LinkButton button, boolean selected) {
        URL resource = MainWindow.class.getClassLoader().getResource(
                "com/openroom/ui/green_star.png");
        URL unselected = MainWindow.class.getClassLoader().getResource(
                "com/openroom/ui/white_star.png");
        if (selected)
            changeStarColor(resource, button);
        else
            changeStarColor(unselected, button);
    }
}